package engine.parsers.impl;

import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.InputSource;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEntry;

import engine.content.IContent;
import engine.content.RSSContent;
import engine.parsers.IParser;
import engine.services.IContentService;

public class ImageFromRSSParser implements IParser {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public IContent parse(IContent content, IContentService contentService)
			throws Exception {
		RSSContent rss = (RSSContent) content;
		SyndEntry entry = rss.getFeedIterator().next();

		String imgStr = null;
		String description = null;

		// first look for media enclosure,
		// if not we will look for the URL from the description
		List<SyndEnclosure> enclosureList = entry.getEnclosures();
		if (enclosureList != null && enclosureList.size() > 0) {
			SyndEnclosure e = enclosureList.get(0);
			imgStr = e.getUrl().toString();
		} else {
			// SyndContent description = entry.getDescription();
			// imgStr = description.getValue();
			// int startImgStr = imgStr.indexOf("src") + 5;
			// int endImgStr = imgStr.indexOf("\"", startImgStr);
			// imgStr = imgStr.substring(startImgStr, endImgStr);

			if (entry.getTitle() != null) {
				description = entry.getTitle();
			}
			String str = entry.getDescription().getValue();
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(str));
			try {
				doc = db.parse(is);
				NamedNodeMap attrs = doc.getDocumentElement().getAttributes();
				imgStr = attrs.getNamedItem("src").getNodeValue();
				if (attrs.getNamedItem("title") != null) {
					if (description == null) description = "";
					description += attrs.getNamedItem("title").getNodeValue();				
				}				
			} catch (Exception e) {
				 SyndContent node = entry.getDescription();
				 imgStr = node.getValue();
				 int startImgStr = imgStr.indexOf("src") + 5;
				 int endImgStr = imgStr.indexOf("\"", startImgStr);
				 imgStr = imgStr.substring(startImgStr, endImgStr);
			}
		}

		IContent myContent = contentService.getResponse(imgStr);
		myContent.setDescription(description);
		return myContent;

	}
}